import { _decorator, Component, Label, Layout, Node, resources, Sprite, SpriteFrame, tween, Vec3 } from 'cc';
import { CardData } from './main/CardData';
import { PokerCard } from './main/PokerCard';
import { PokerRule } from './main/PokerRule';
import { Card, GameMode } from './main/Card';
const { ccclass, property } = _decorator;

@ccclass('Player')
export class Player extends Component {
    @property({ type: Label, visible(this: Player) { return !this.isBottomPlayer }})
    cardCountLabel: Label = null!;

    @property({ type: Node, visible(this: Player) { return this.isBottomPlayer }})
    handArea: Node = null!;

    @property public isBottomPlayer = false;
    
    private _cards: CardData[] = [];
    private _sortOrder = [15,14,13,12,11,10,9,8,7,6,5,4,3]; // 2 > A > K > ... > 3

    public gameMode: GameMode = GameMode.BANZIPAO;

    get cards() { return this._cards.slice(); }

    onLoad() {
        this.validateComponents();
    }

    addCard(card: CardData) {
        this._cards.push(card);
        this.sortHandCards();
        this.updateUI();
    }

    private sortHandCards() {
        // 主排序：数值倒序，次排序：花色正序
        this._cards.sort((a, b) => {
            const aVal = this._sortOrder.indexOf(a.value);
            const bVal = this._sortOrder.indexOf(b.value);
            
            if (aVal !== bVal) return aVal - bVal;
            return a.suit - b.suit;
        });

        this.updateCardNodesOrder();
    }

    // 提示方法
    public showInvalidTip() {
        console.log("Invalid card combination!");
        // 实际实现中可以播放动画或显示提示
    }

    public showCardTypeTip(typeName: string) {
        console.log(`Played: ${typeName}`);
        // 实现提示显示逻辑
    }

    private updateCardNodesOrder() {
        if (!this.isBottomPlayer || !this.handArea) return;

        this.validateCardNodes();

        this._cards.forEach((cardData, index) => {
            const cardNode = this.handArea.children.find(n => {
                const pc = n.getComponent(PokerCard);
                return pc?.data?.value === cardData.value && 
                       pc?.data?.suit === cardData.suit;
            });

            // 保持卡牌层级关系
        cardNode.setSiblingIndex(index);
        
        // 重置选中状态
        cardNode.getComponent(PokerCard)?.resetState();
            
            cardNode?.setSiblingIndex(index);
        });
        // 强制更新布局
    this.scheduleOnce(() => {
        const layout = this.handArea.getComponent(Layout);
        layout?.updateLayout();
    }, 0);
    }

    private validateCardNodes() {
        const invalidNodes = this.handArea.children.filter(n => 
            !n.getComponent(PokerCard)?.data
        );
        
        invalidNodes.forEach(n => {
            console.warn("Removing invalid card node:", n.name);
            n.destroy();
        });
    }

    private updateUI() {
        if (!this.cardCountLabel?.node?.isValid) {
            console.warn(`[${this.node.name}] CardCountLabel is missing`);
            return;
        }
    
        if (!this.cardCountLabel.node.parent?.isValid) {
            console.warn(`[${this.node.name}] CardCount parent node is missing`);
            return;
        }
    
        this.cardCountLabel.string = `${this._cards.length}`;
        this.cardCountLabel.node.parent.active = this._cards.length > 0;
    }

    private validateComponents() {
        if (!this.isBottomPlayer) {
            if (!this.cardCountLabel) {
                console.error(`[${this.node.name}] Missing CardCountLabel reference`);
                this.enabled = false;
            }
            
            if (this.cardCountLabel && !this.cardCountLabel.node.parent) {
                console.error(`[${this.node.name}] CardCountLabel has no parent`);
                this.enabled = false;
            }
        }
    }

    public tryPlayCards(selectedCards: CardData[]): boolean {
        const cards = selectedCards.map(c => new Card(
            c.suit - 1, // 转换花色索引
            c.value,
            `${c.suit}_${c.value}`
        ));
        
        const result = PokerRule.checkCards(cards, this.gameMode);
        
        if (result.type === 'invalid') {
            this.showInvalidTip();
            return false;
        }
        
        this.playValidCards(selectedCards, result);
        return true;
    }
    
    private playValidCards(cards: CardData[], result: any) {
        // 移除手牌并更新UI
        this._cards = this._cards.filter(c => 
            !cards.some(sc => sc.value === c.value && sc.suit === c.suit)
        );
        
        this.sortHandCards();
        this.updateUI();
        
        // 显示牌型提示
        this.showCardTypeTip(result.displayName);
    }
}


